import { Component, OnDestroy, OnInit } from '@angular/core';
import { PingPongService } from './service/ping-pong/ping-pong.service';
import { ServerConnectionStatusService } from './service/server-connection-status/server-connection-status.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  private subscribedServices: Subscription[] = [];

  isCollapsed = false;

  isServerConnected: boolean;

  constructor(private serverConnectionStatusService: ServerConnectionStatusService,
              private pingPongService$: PingPongService) { }

  ngOnInit(): void {
    // Subscribe the server connection status
    this.subscribedServices.push(this.serverConnectionStatusService.isServerConnected.subscribe(it => {
      if (this.isServerConnected !== it) {
        this.isServerConnected = it;
      }
    }));

    // Ping the server to see if it's connected every 3 seconds
    setInterval(() => {
      this.pingPongService$.ping().subscribe(_ => {
        this.serverConnectionStatusService.isServerConnected.next(true);
      }, _ => {
        this.serverConnectionStatusService.isServerConnected.next(false);
      });
    }, 3000);
  }

  ngOnDestroy(): void {
    for (const service of this.subscribedServices) {
      service.unsubscribe();
    }
  }
}
